package com.jackrain.nea.fc.pos.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.QueryCpUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.pos.api.ViewDLStoreBillToF4QueryCmd;
import com.jackrain.nea.fc.pos.mapper.ViewDLStoreBillToF4Mapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 零售对账单
 *
 * @author wuwenxue
 * @date 2018/05/22
 **/
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "pos")
public class ViewDLStoreBillToF4QueryCmdImpl extends CommandAdapter implements ViewDLStoreBillToF4QueryCmd {

    private final static FastDateFormat DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd");

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {
        ValueHolder vh = new ValueHolder();
        ViewDLStoreBillToF4Mapper viewDLStoreBillToF4Mapper = ApplicationContextHandle.getBean(
                ViewDLStoreBillToF4Mapper.class);
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(
                map.get("param"), "yyyy-MM-dd HH:mm:ss"), Feature.OrderedField);
        log.info("ViewDLStoreBillToF4QueryCmdImpl-->param-->{}",param);

        if (null == param || (!param.containsKey("IDS")) || param.getJSONArray("IDS").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }

        Object[] ids = param.getJSONArray("IDS").toArray();
        JSONArray jsonArray = new JSONArray();
        String action = param.getString("action");

        if ("account".equals(action) || "save".equals(action) || "add".equals(action)) {
            //记账/保存
            List<HashMap> list = viewDLStoreBillToF4Mapper.selStoreBillData(ids);
            for (HashMap hashMap : list) {
                if (null != hashMap.get("CP_C_STORE_ID")) {
                    Long storeID = TypeUtils.castToLong(hashMap.get("CP_C_STORE_ID"));

                    Date billDate = TypeUtils.castToDate(hashMap.get("BILL_DATE"));
                    String formatBillDate = DATE_FORMAT.format(billDate);

                    hashMap.put("BILL_DATE", formatBillDate);

                    //跨库查询
                    JSONObject whereJs = new JSONObject();
                    whereJs.put("ID", storeID);
                    HashMap h = QueryCpUtil.queryCP("CP_C_STORE", "ECODE", whereJs);

                    if (null != h && h.size() > 0) {
                        //店仓编码
                        hashMap.put("CP_C_STORE_ECODE", h.get("ECODE"));
                    } else {
                        throw new NDSException("店仓 查询为空！  店仓ID：" + storeID);
                    }
                }

                Long id = TypeUtils.castToLong(hashMap.get("ID"));
                List<HashMap> itemList = viewDLStoreBillToF4Mapper.selStoreBillItemData(id);
                JSONArray itemArray = new JSONArray();
                for (HashMap itemH : itemList) {
                    String bill_no = (String) itemH.get("BILL_NO");

                    List<HashMap> retailList = viewDLStoreBillToF4Mapper.selRetailStoreData(bill_no);
                    JSONArray retailArray = new JSONArray();
                    for(HashMap retailMap : retailList){
                        retailArray.add(retailMap.get("BILL_NO"));
                    }
                    itemH.put("RETAIL_NO", retailArray);
                    itemH.put("COUPON_AMOUNT", 0);
                    itemH.put("ONLINE_AMOUNT", 0);
                    JSONObject itemjs = new JSONObject(itemH);
                    itemArray.add(itemjs);
                }

                JSONObject js = new JSONObject(hashMap);
                js.put("DL_B_STORE_BILL_ITEM", itemArray);
//                log.debug("零售对账单-F4---------->"+js);
                log.debug("ViewDLStoreBillToF4QueryCmdImpl--js-->{}",js);

                JSONObject param1 = JSON.parseObject(JSON.toJSONStringWithDateFormat(js,
                        "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
                jsonArray.add(param1);
            }
        } else if ("unaccount".equals(action)) {
            //取消记账
            List<HashMap> list = viewDLStoreBillToF4Mapper.selStoreBillData(ids);

            for (HashMap hashMap : list) {
                JSONObject unSumJson = new JSONObject();
                Long storeID = TypeUtils.castToLong(hashMap.get("CP_C_STORE_ID"));
                //跨库查询
                JSONObject whereJs = new JSONObject();
                whereJs.put("ID", storeID);
                HashMap h = QueryCpUtil.queryCP("CP_C_STORE", "ECODE", whereJs);

                if (null != h && h.size() > 0) {
                    //店仓编码
                    unSumJson.put("USERDEFINE1", h.get("ECODE"));
                } else {
                    throw new NDSException("店仓 查询为空！  店仓ID：" + storeID);
                }

                Date billDate = TypeUtils.castToDate(hashMap.get("BILL_DATE"));
                String formatBillDate = DATE_FORMAT.format(billDate);


                unSumJson.put("BILL_TYPE", "RETAIL_CHARGE");
                unSumJson.put("BILL_NO", hashMap.get("BILL_NO"));
                unSumJson.put("USERDEFINE2", formatBillDate);
                unSumJson.put("STATUS_TYPE", "UNCHARG");
                unSumJson.put("OPR_ECODE", hashMap.get("MODIFIEDNAME"));
                unSumJson.put("OPR_ENAME", hashMap.get("MODIFIEDENAME"));
                unSumJson.put("OPR_DATE", hashMap.get("MODIFIEDDATE"));

                JSONObject param1 = JSON.parseObject(JSON.toJSONStringWithDateFormat(unSumJson,
                        "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
                jsonArray.add(param1);
            }
        }

        vh.put("data", jsonArray);
        return vh;
    }


//    /**
//     * 跨库查询
//     */
//    public JSONObject queryCP(String tablename, String fileds, JSONObject wherejo) {
//        HashMap hashMap = new HashMap();
//        hashMap.put("tableName", tablename);
//        hashMap.put("fields", fileds);
//        hashMap.put("whereKeys", wherejo);
//        hashMap.put("type", HashMap.class);
//        String erpUrl = pconf.getProperty("fc.edas.url", "");
//        URI uri = null;
//        try {
//            uri = new URI(erpUrl + "/fc/api/query");
//        } catch (URISyntaxException e) {
//            e.printStackTrace();
//        }
//        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
//        JSONObject paramObject = new JSONObject();
//        paramObject.put("address", "com.jackrain.nea.web.QueryCmd");
//        paramObject.put("group", "cp");
//        paramObject.put("version", "2");
//        byte[] querymap = serializer.serialize(hashMap);
//        try {
//            paramObject.put("map", new String(querymap, "ISO-8859-1"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        map.add("param", paramObject.toJSONString());
//        String retStr = restTemplateUtil.doPostForm(uri, map);
//        JSONObject selectMenuType = JSON.parseObject(retStr).getJSONObject("data");
//
//        return selectMenuType;
//    }

}
